package action;

import gate.ActionHandler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import bean.shoppingCard.ProductDetail;
import bean.user.SessionUser;
import dm.ProductDM;

public class ActionProduct implements ActionHandler{
	
	@Override
	public void handleAction(HttpServletRequest req, HttpServletResponse res) {

		try {
			ProductDM dm = new ProductDM();
			String url = req.getParameter("url");
			String action = req.getParameter("action");
			
			if(action.equals("getProduct")){
				
				try {
					int proId = Integer.parseInt(req.getParameter("proId"));
					HttpSession s = req.getSession();
					SessionUser user = (SessionUser) s.getAttribute("user");
					
					ProductDetail product = dm.openProduct(proId, user.getUserId());
					req.setAttribute("product",product);
					
				} catch (Exception e) {
					req.setAttribute("error", "Error !"+e.getMessage());
				}
				
			}else if(action.equals("closeProduct")){
				
				try {
					int proId = Integer.parseInt(req.getParameter("proId"));
					HttpSession s = req.getSession();
					SessionUser user = (SessionUser) s.getAttribute("user");
					
					dm.closeProduct(proId, user.getUserId());
					
				} catch (Exception e) {
					req.setAttribute("error", "Error !"+e.getMessage());
				}
				

			}else{
				req.setAttribute("error", "Action not found !");
			}
			
			req.getRequestDispatcher(url).forward(req, res);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
